package com.hnjfzn.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnjfzn.common.core.constant.UserConstants;
import com.hnjfzn.common.core.exception.ServiceException;
import com.hnjfzn.common.core.utils.AreaUtil;
import com.hnjfzn.common.core.utils.SpringUtils;
import com.hnjfzn.common.core.utils.StringUtils;
import com.hnjfzn.common.datascope.annotation.DataScope;
import com.hnjfzn.common.security.utils.SecurityUtils;
import com.hnjfzn.system.api.domain.SysArea;
import com.hnjfzn.system.api.domain.SysUser;
import com.hnjfzn.system.mapper.SysAreaMapper;
import com.hnjfzn.system.service.ISysAreaService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysArea> implements ISysAreaService {

    @Override
    @DataScope(areaAlias = "a")
    public List<SysArea> list(SysArea area) {
        return baseMapper.listByObj(area);
    }

    @Override
    public void checkDataScope(String areaId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && StringUtils.isNotNull(areaId))
        {
            SysArea area = new SysArea();
            area.setAreaId(areaId);
            List<SysArea> areas = SpringUtils.getAopProxy(this).list(area);
            if (StringUtils.isEmpty(areas))
            {
                throw new ServiceException("没有权限访问区域数据！");
            }
        }
    }

    @Override
    public boolean existsNormalChild(String areaId) {
        return exists(new QueryWrapper<SysArea>().eq("status", UserConstants.AREA_NORMAL).like("parent_id", AreaUtil.getFuzzyQuery(areaId)));
    }

    @Override
    public boolean existsChild(String areaId) {
        return exists(new QueryWrapper<SysArea>().eq("del_flag", UserConstants.AREA_NORMAL).like("parent_id", AreaUtil.getFuzzyQuery(areaId)));
    }

    @Override
    public boolean checkExistUser(String areaId) {
        return baseMapper.checkExistUser(areaId) > 0;
    }

    @Override
    public boolean removeArea(String areaId) {
        SysArea area = new SysArea();
        area.setAreaId(areaId);
        area.setDelFlag("2");
        area.setUpdateBy(SecurityUtils.getUsername());
        area.setUpdateTime(new Date());
        return updateById(area);
    }
}
